//
//  HomeViewController.m
//  TNS
//
//  Created by parkin on 16/3/6.
//  Copyright © 2016年 zhongyan. All rights reserved.
//

#import "HomeViewController.h"

@interface HomeViewController ()
@property (nonatomic, strong, readonly) UIBarButtonItem *backBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *forwardBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *refreshBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *stopBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *homeBarButtonItem;
@property (nonatomic, strong, readonly) UIBarButtonItem *actionBarButtonItem;
@property (nonatomic, strong, readonly) UIActionSheet *pageActionSheet;
@end

@implementation HomeViewController
@synthesize backBarButtonItem, forwardBarButtonItem, refreshBarButtonItem, stopBarButtonItem,homeBarButtonItem, actionBarButtonItem, pageActionSheet;
@synthesize _progressView;
@synthesize _progressProxy;
- (UIWebView *)mainWebView {
    if (!_mainWebView) {
        _mainWebView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _mainWebView;
}
#pragma mark - setters and getters
- (UIBarButtonItem *)backBarButtonItem {
    
    if (!backBarButtonItem) {
        UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [back setImage:[UIImage imageNamed:@"back_02"] forState:UIControlStateNormal];
        [back addTarget:self action:@selector(goBackClicked:) forControlEvents:UIControlEventTouchUpInside];
        backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
        
    }
    return backBarButtonItem;
}

- (UIBarButtonItem *)forwardBarButtonItem {
    
    if (!forwardBarButtonItem) {
        UIButton *forward = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [forward setImage:[UIImage imageNamed:@"go_02"] forState:UIControlStateNormal];
        [forward addTarget:self action:@selector(goForwardClicked:) forControlEvents:UIControlEventTouchUpInside];
        forwardBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:forward];
    }
    return forwardBarButtonItem;
}

- (UIBarButtonItem *)refreshBarButtonItem {
    
    if (!refreshBarButtonItem) {
        UIButton *refresh = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [refresh setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
        [refresh addTarget:self action:@selector(reloadClicked:) forControlEvents:UIControlEventTouchUpInside];
        refreshBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:refresh];
    }
    
    return refreshBarButtonItem;
}

- (UIBarButtonItem *)homeBarButtonItem {
    if (!homeBarButtonItem) {
        UIButton *home = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [home setImage:[UIImage imageNamed:@"home"] forState:UIControlStateNormal];
        [home addTarget:self action:@selector(homeClicked:) forControlEvents:UIControlEventTouchUpInside];
        homeBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:home];
    }
    return homeBarButtonItem;
}
- (UIBarButtonItem *)actionBarButtonItem {
    
    if (!actionBarButtonItem) {
        UIButton *action = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 15, 15)];
        [action setImage:[UIImage imageNamed:@"logout"] forState:UIControlStateNormal];
        [action addTarget:self action:@selector(actionButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        actionBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:action];
    }
    return actionBarButtonItem;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar addSubview:_progressView];
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    
    self.mainWebView.delegate = _progressProxy;
    self.title = @"悠享车生活";
    self.navigationController.hidesBarsOnSwipe = YES;
    self.mainWebView.scalesPageToFit = YES;
    self.mainWebView.scrollView.bounces = NO;
    NSHTTPCookieStorage *cook = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    [cook setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.autoyou.com.cn"]];
    [self.mainWebView loadRequest:request];
    [self.view addSubview:self.mainWebView];
    // Do any additional setup after loading the view.
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        [self.mainWebView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    }
    if (toInterfaceOrientation == UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
        [self.mainWebView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    }
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        [self.mainWebView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    }
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_progressView removeFromSuperview];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        [self.navigationController setToolbarHidden:YES animated:animated];
    }
}
- (void)viewDidUnload {
    
    [super viewDidUnload];
    _mainWebView = nil;
    backBarButtonItem = nil;
    forwardBarButtonItem = nil;
    refreshBarButtonItem = nil;
    stopBarButtonItem = nil;
    actionBarButtonItem = nil;
    pageActionSheet = nil;
}
- (void)loadWebView {
    [self.navigationController.navigationBar addSubview:_progressView];
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    self.mainWebView.delegate = _progressProxy;
    self.mainWebView.scalesPageToFit = YES;
    self.mainWebView.scrollView.bounces = NO;
    NSHTTPCookieStorage *cook = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    [cook setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.autoyou.com.cn"]];
    [self.mainWebView loadRequest:request];
    self.view = self.mainWebView;
}
#pragma mark - NJKWebViewProgressDelegate

-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        return YES;
    
    return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}



- (void)viewWillAppear:(BOOL)animated {
    NSAssert(self.navigationController, @"SVWebViewController needs to be contained in a UINavigationController. If you are presenting SVWebViewController modally, use SVModalWebViewController instead.");
    [super viewWillAppear:animated];
    //    [self loadWebView];
    self.navigationController.toolbarHidden = YES;
//    self.navigationController.toolbar.backgroundColor = [UIColor clearColor];
//    [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"foot_black"] forToolbarPosition:UIBarPositionBottom barMetrics:UIBarMetricsDefault];
    self.navigationItem.hidesBackButton = YES;
    [self.navigationController.navigationBar addSubview:_progressView];
//    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
//        [self.navigationController setToolbarHidden:NO animated:animated];
//    }
}
- (void)updateToolbarItems {
//    self.backBarButtonItem.enabled = self.mainWebView.canGoBack;
//    self.navigationItem.hidesBackButton = YES;
//    self.forwardBarButtonItem.enabled = self.mainWebView.canGoForward;
//    self.actionBarButtonItem.enabled = !self.mainWebView.isLoading;
//    
//    //    UIBarButtonItem *refreshStopBarButtonItem = self.mainWebView.isLoading ? self.stopBarButtonItem : self.refreshBarButtonItem;
//    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//    fixedSpace.width = 5.0f;
//    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//    
//    NSArray *items;
//    UIToolbar *toolbar = [[UIToolbar alloc] init];
//    toolbar.items = items;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolbar];
//    items = [NSArray arrayWithObjects:
//             fixedSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             flexibleSpace,
//             self.actionBarButtonItem,
//             fixedSpace,
//             nil];
//    
//    self.toolbarItems = items;
}

#pragma mark -
#pragma mark UIWebViewDelegate
- (BOOL)webView:(nonnull UIWebView *)webView shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self updateToolbarItems];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
    //    self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [self updateToolbarItems];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateToolbarItems];
}

#pragma mark - Target actions

- (void)goBackClicked:(UIButton *)sender {
    [self.mainWebView goBack];
}

- (void)goForwardClicked:(UIButton *)sender {
    [self.mainWebView goForward];
}

- (void)reloadClicked:(UIButton *)sender {
    [self.mainWebView reload];
}
- (void)homeClicked:(UIButton *)sender {
    [self loadWebView];
}
- (void)stopClicked:(UIBarButtonItem *)sender {
    [self.mainWebView stopLoading];
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateToolbarItems];
}
- (void)actionButtonClicked:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
